<template>
  <div class="add-article">
    <nav-bar :left-text="'取消'">
      <div class="push-btn" @click="onPublish">发布</div>
    </nav-bar>
    <div class="main">
      <van-form ref="formRef">
        <van-cell-group inset>
          <van-field
            v-model="name"
            name="name"
            label="标题"
            placeholder="请输入标题"
            :rules="[{ required: true, message: '请输入标题' }]"
          />
          <van-field
            v-model="tagName"
            is-link
            readonly
            name="tag"
            label="类别"
            placeholder="点击选择类别"
            @click="showPicker = true"
          />
          <van-popup v-model:show="showPicker" position="bottom">
            <van-picker
              :columns="columns"
              @confirm="onConfirm"
              @cancel="showPicker = false"
            />
          </van-popup>
          <van-field
            v-model="content"
            name="content"
            label="内容"
            rows="5"
            type="textarea"
            placeholder="请输入内容"
            :rules="[{ required: true, message: '请填写内容' }]"
          />
          <van-field name="uploader" label="文件上传">
            <template #input>
              <van-uploader
                v-model="fileList"
                :after-read="onAfterRead"
                :before-delete="onBeforeDelete"
              />
            </template>
          </van-field>
        </van-cell-group>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInstance, Toast, UploaderFileListItem } from 'vant'
import * as qiniu from 'qiniu-js'
import NavBar from '../../../components/nav-bar.vue'
import { getUploadToken } from '../../../service/upload'
import { createArticle } from '../../../service/article'
import { getTags } from '../../../service/tag'
import { tagsRes } from '../../../service/tag/types'

const router = useRouter()
const name = ref<string>('')
const content = ref<string>('')
const formRef = ref<FormInstance>()
const imgList = ref<string[]>([])
const uploadToken = ref<string>('')
const fileList = ref<UploaderFileListItem[]>()
const tagName = ref<string>('')
const showPicker = ref<boolean>(false)
const columns = ref<string[]>([])
const tags = ref<tagsRes.Tag[]>([])
const tagId = ref<number>()

const onPublish = () => {
  formRef.value?.validate().then(async () => {
    if (!tagId.value) {
      Toast('请选择类别')
      return
    }
    const res = await createArticle(
      name.value,
      content.value,
      imgList.value,
      tagId.value
    )
    console.log(res)
    router.push(`/article/${res.data.article.id}`)
  })
}
const onBeforeDelete = (
  file: File,
  detail: { name: string; index: number }
) => {
  imgList.value.splice(detail.index, 1)
  return true
}
const onAfterRead = async (
  items: UploaderFileListItem | UploaderFileListItem[]
) => {
  const item = items as UploaderFileListItem
  item.status = 'uploading'
  if (!item.file) return
  if (!uploadToken.value) {
    const res = await getUploadToken()
    uploadToken.value = res.data.uploadToken
  }
  qiniu
    .compressImage(item.file, {
      quality: 0.2,
      noCompressIfLarger: true
    })
    .then((data) => {
      const observable = qiniu.upload(
        data.dist as File,
        null,
        uploadToken.value
      )
      observable.subscribe({
        error() {
          item.status = 'failed'
        },
        complete(res) {
          imgList.value.push(res.url)
          item.status = 'done'
        }
      })
    })
}
const onConfirm = (name: string) => {
  tagName.value = name
  const tag = tags.value?.find((item) => item.name === name)
  tagId.value = tag?.id
  showPicker.value = false
}
const loadTags = async () => {
  const res = await getTags()
  tags.value = res.data.tags
  res.data.tags.forEach((item) => {
    columns.value.push(item.name)
  })
}

onMounted(() => {
  loadTags()
})
</script>

<style lang="scss" scoped>
.add-article {
  background-color: #fff;
  height: 100%;
  .push-btn {
    color: #48a0fc;
  }
}
</style>
